<script lang="ts" setup>
import type { InfraConfigApi } from '#/api/infra/config';

import { onMounted, ref } from 'vue';

import { Page } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import {
  Alert,
  Button,
  Card,
  Form,
  Input,
  message,
  Select,
} from 'ant-design-vue';

import { getBrandList } from '#/api/ai/llm/brand';
import { list, updateBatch } from '#/api/infra/config';
// 定义安全配置类型
interface Config {
  model_of_chat?: InfraConfigApi.Config;
  chatgpt_endpoint?: InfraConfigApi.Config;
  chatgpt_chatPath?: InfraConfigApi.Config;
  chatgpt_api_key?: InfraConfigApi.Config;
  chatgpt_model_name?: InfraConfigApi.Config;
  ai_ollama_host?: InfraConfigApi.Config;
  chatgpt_test_img?: InfraConfigApi.Config;
}
// 定义大模型选项类型
interface LlmOption {
  label: string;
  value: string;
  extra: Map<string, string>;
}

// 状态管理
const llmSelectItems = ref<LlmOption[]>([]);
const currentLlm = ref<string | undefined>(undefined);
const formRef = ref<any>(null);
const queryForm = {
  category: 'CHATMODEL',
};
// 表单数据
const formData = ref({
  model_of_chat: '',
  chatgpt_endpoint: '',
  chatgpt_chatPath: '',
  chatgpt_api_key: '',
  chatgpt_model_name: '',
  ai_ollama_host: '',
  chatgpt_test_img: '',
});
const oldForm = ref({
  model_of_chat: '',
  chatgpt_endpoint: '',
  chatgpt_chatPath: '',
  chatgpt_api_key: '',
  chatgpt_model_name: '',
  ai_ollama_host: '',
  chatgpt_test_img: '',
});
const configList = ref<Config>({
  model_of_chat: { name: '对话模型供应商' },
  chatgpt_endpoint: { name: '大模型接入地址' },
  chatgpt_chatPath: { name: '大模型对话路径' },
  chatgpt_api_key: { name: '大模型API Key' },
  chatgpt_model_name: { name: '大模型名称' },
  ai_ollama_host: { name: '本地Ollama地址' },
  chatgpt_test_img: { name: '测试图片' },
});
const isUpdate = ref(false);
// 页面初始化
onMounted(() => {
  // 获取大模型供应商列表
  getData();
  // 获取已配置的数据
  getConfig();
});
const getData = async () => {
  const data = await getBrandList();

  const llmList = data.map((item: any) => {
    const extra = new Map<string, string>();
    extra.set('llmEndpoint', item.options.llmEndpoint);
    extra.set('chatPath', item.options.chatPath);

    return {
      label: item.title,
      value: item.key,
      extra,
    } as LlmOption;
  });

  llmSelectItems.value = llmList;
};

const getConfig = async () => {
  try {
    const data = await list(queryForm);
    if (data && data.length > 0) {
      const configList = data.reduce(
        (obj: Config, option: InfraConfigApi.Config) => {
          obj[option.key] = { ...option };
          formData.value[option.key] = option.value;
          oldForm.value[option.key] = option.value;
          return obj;
        },
        {},
      );
      // 根据key 和原有的configList 合并
      configList.value = { ...configList.value, ...configList };
    }
  } catch (error) {
    message.error('加载对话模型配置信息失败');
    console.error('Failed to load security config:', error);
  }
};
// 处理大模型选择变化
const handleLlmChange = (value: string, option: LlmOption | undefined) => {
  if (value) {
    currentLlm.value = value;
    formData.value = {
      ...formData.value,
      chatgpt_endpoint: option.extra.get('llmEndpoint') || '',
      chatgpt_chatPath: option.extra.get('chatPath') || '',
      chatgpt_api_key: '',
      chatgpt_model_name: '',
      model_of_chat: value,
    };
  } else {
    currentLlm.value = undefined;
  }
};
// 保存安全配置
const handleSave = async () => {
  const valid = await formRef.value.validate().catch(() => false);
  if (!valid) return false;
  try {
    await updateBatch(
      Object.entries(formData.value).map(([key, value]) => {
        return {
          id: configList.value[key]?.id,
          key,
          value,
          name: configList.value[key]?.name,
          visible: false,
          category: 'CHATMODEL',
          type: 1,
          remark: configList.value[key]?.remark,
        } as InfraConfigApi.Config;
      }),
    );
    oldForm.value = Object.assign({}, formData.value);
    isUpdate.value = false;
    message.success('保存成功');
  } catch (error) {
    message.error('保存失败');
    console.error('Failed to save chatgpt config:', error);
  }
};
// 修改
const onUpdate = () => {
  isUpdate.value = true;
};

// 取消
const handleCancel = () => {
  formData.value = Object.assign({}, oldForm.value);
  isUpdate.value = false;
};
</script>

<template>
  <div style="display: flex; justify-content: center">
    <Page style="width: 80%">
      <Card title="本地Ollama模型参数">
        <Form
          ref="formRef"
          :model="formData"
          label-align="left"
          :disabled="!isUpdate"
          :label-col="{ span: 3 }"
        >
          <Form.Item label="Ollama地址" name="ai_ollama_host">
            <Input
              placeholder="请输入本地Ollama模型地址"
              v-model:value="formData.ai_ollama_host"
            />
          </Form.Item>
        </Form>
      </Card>
      <Card title="对话模型配置" style="margin-top: 12px">
        <Alert
          message="注意：有很多大模型（比如：暗月之面等）都是兼容 ChatGPT 的，因此若需要配置系统未内置的平台的大模型，供应商可以选择OpenAi。"
          type="info"
        />

        <Form
          style="margin-top: 12px"
          ref="formRef"
          :model="formData"
          label-align="left"
          :disabled="!isUpdate"
          :label-col="{ span: 3 }"
        >
          <Form.Item label="对话模型供应商" name="model_of_chat">
            <Select
              allow-clear
              show-search
              placeholder="选择对话模型供应商"
              v-model:value="formData.model_of_chat"
              :options="llmSelectItems"
              :filter-option="
                (input, option) => {
                  return (option?.label || '')
                    .toLowerCase()
                    .includes(input.toLowerCase());
                }
              "
              @change="handleLlmChange"
            />
          </Form.Item>
          <Form.Item label="Endpoint" name="chatgpt_endpoint">
            <Input
              placeholder="请输入大模型接入地址"
              v-model:value="formData.chatgpt_endpoint"
            />
          </Form.Item>

          <Form.Item label="chatPath" name="chatgpt_chatPath">
            <Input
              placeholder="请输入大模型聊天路径"
              v-model:value="formData.chatgpt_chatPath"
            />
          </Form.Item>

          <Form.Item label="ApiKey" name="chatgpt_api_key">
            <Input
              placeholder="请输 Api Key"
              v-model:value="formData.chatgpt_api_key"
            />
          </Form.Item>

          <Form.Item label="模型名称" name="chatgpt_model_name">
            <Input
              placeholder="请输入模型名称"
              v-model:value="formData.chatgpt_model_name"
            />
          </Form.Item>
        </Form>
      </Card>
      <Card title="多模态配置" style="margin-top: 12px">
        <Form
          ref="formRef"
          :model="formData"
          label-align="left"
          :disabled="!isUpdate"
          :label-col="{ span: 3 }"
        >
          <Form.Item label="测试图片" name="chatgpt_test_img">
            <Input
              placeholder="请输入测试图片地址"
              v-model:value="formData.chatgpt_test_img"
            />
          </Form.Item>
        </Form>
      </Card>
      <div style="float: right; margin-top: 12px">
        <Button
          type="primary"
          @click="onUpdate"
          v-if="!isUpdate"
          :disabled="false"
        >
          <IconifyIcon icon="lucide:edit" /> 修改
        </Button>
        <Button
          v-if="isUpdate"
          :disabled="false"
          type="primary"
          @click="handleSave"
        >
          <IconifyIcon icon="lucide:save" /> 保存
        </Button>
        <Button
          @click="handleCancel"
          style="margin-left: 20px"
          :disabled="false"
          v-if="isUpdate"
        >
          <IconifyIcon icon="lucide:shield-close" /> 取消
        </Button>
      </div>
    </Page>
  </div>
</template>

<style lang="scss" scoped>
/* 设置滚动条样式 */
</style>
